<?php

namespace app\admin\controller\mental;

use app\common\controller\Backend;
use app\admin\library\Auth;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 推广管理
 *
 * @icon fa fa-circle-o
 */
class Extension extends Backend
{

    /**
     * Extension模型对象
     * @var \app\admin\model\mental\Extension
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mental\Extension;
        $this->view->assign("channelTypeList", $this->model->getChannelTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'createtime', 'updatetime', 'url', 'channel_type', 'status', 'user_id', 'total_commission', 'total_order', 'total_deduction']);
                $row->visible(['user']);
                $row->getRelation('user')->visible(['mobile', 'nickname', 'money']);
                // $row->visible(['testmain']);
                // $row->getRelation('testmain')->visible(['title']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }



    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($params['ratio'] > 0.95) {
                    $this->error('您的设置已超出运营成本');
                }
                if ($params['ratio'] < 0.1) {
                    $this->error('老板不要太扣');
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }



                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    // $mainIdsArr = explode(',', $params['main_ids']);
                    $channel_type = $params['channel_type'];

                    // unset($params['main_ids']);
                    unset($params['channel_type']);
                    $paramsData = [];
                    // foreach ($mainIdsArr as $v) {
                    foreach ($channel_type as $vv) {
                        $isData = $this->model->where(['user_id' => $params['user_id'], 'channel_type' => $vv])->find();
                        if (!$isData) {
                            $arr = $params;
                            // $arr['main_id'] = $v;
                            $arr['channel_type'] = $vv;
                            $paramsData[] = $arr;
                        }
                    }
                    // }

                    $result = $this->model->allowField(true)->saveAll($paramsData);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($params['ratio'] > 0.95) {
                    $this->error('您的设置已超出运营成本');
                }
                if ($params['ratio'] < 0.1) {
                    $this->error('老板不要太扣');
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }







    public function daochu($ids = null)
    {
        // set_time_limit(0);
        // $filter = $this->request->get('filter');
        // $op = $this->request->get('op');

        // $this->request->get(['filter' => $filter, 'op' => $op]);
        // list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        //根据店铺分组 并获取分页数据

        // $list = \think\Db::name('mental_extension')
        //     ->alias('e')
        //     ->join('mental_testmain mt','mt.id=e.main_id')
        //     ->join('user u','u.id=e.user_id')
        //     ->where(['e.id'=>['IN',$ids]])
        //     ->field('e.*,u.nickname,u.mobile,mt.title')
        //     // ->order($sort, $order)
        //     // ->limit($offset, $limit)
        //     ->select();
        $list = $this->model
            ->with(['user'])
            ->where(['extension.id' => ['IN', $ids]])
            ->select()->toArray();

        $mainList = \think\Db::name('mental_testmain')->where('switch', 1)->select();

        $data = [];
        foreach ($mainList as $k => $v) {
            foreach ($list as $kk => $vv) {
                $data[] = [
                    'fxId' => $vv['id'], //分销id
                    'nickname' => $vv['user']['nickname'], //推广人
                    'mobile' => $vv['user']['mobile'], //手机号
                    'title' => $v['title'], //产品名称
                    'url' => config('site.qdDomain') . '/pages/cpxq?id=' . $v['id'] . '&fxId=' . $vv['id'], //分销链接
                    'channelName' => $vv['channel_type_text'], //渠道名称


                ];
            }
        }



        $this->exportOrderExcel($data);
    }


    public function exportOrderExcel($data)
    {
        require THINK_PATH . 'PHPExcel-1.8/Classes/PHPExcel.php';


        // 新建一个excel对象 大神已经加入了PHPExcel 不用引了 直接用！
        $objPHPExcel = new \PHPExcel();  //在vendor目录下 \不能少 否则报错


        $objPHPExcel->getDefaultStyle()->getFont()->setName('微软雅黑'); //字体

        $myrow = 1;/*表头所需要行数的变量，方便以后修改*/

        // var_dump($data);die;
        /*表头数据填充*/
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(30);/*设置行高*/
        $objPHPExcel->setActiveSheetIndex(0)  //设置一张sheet为活动表 添加表头信息 
            ->setCellValue('A' . $myrow, '分销ID')
            ->setCellValue('B' . $myrow, '推广人')
            ->setCellValue('C' . $myrow, '手机号')
            ->setCellValue('D' . $myrow, '分销产品')
            ->setCellValue('E' . $myrow, '推广链接')
            ->setCellValue('F' . $myrow, '推广渠道');
        // 关键数据
        // var_dump($data);die;
        // $data = json_decode($data, true);
        $myrow = $myrow + 1; //刚刚设置的行变量
        $mynum = 1; //序号
        //遍历接收的数据，并写入到对应的单元格内
        foreach ($data as $key => $value) {
            $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $myrow, $value['fxId'])
                ->setCellValue('B' . $myrow, $value['nickname'])
                ->setCellValue('C' . $myrow, $value['mobile'])
                ->setCellValue('D' . $myrow, $value['title'])
                ->setCellValue('E' . $myrow, $value['url'])
                ->setCellValue('F' . $myrow, $value['channelName']);
            $objPHPExcel->getActiveSheet()->getRowDimension('' . $myrow)->setRowHeight(20);/*设置行高 不能批量的设置 这种感觉 if（has（蛋）！=0）{疼();}*/
            $myrow++;
            $mynum++;
        }



        $mynumdata = $myrow - 1; //获取主要数据结束的行号
        $objPHPExcel->setActiveSheetIndex(0)->getstyle('A1:F' . $mynumdata)->getAlignment()->setHorizontal(\PHPExcel_style_Alignment::HORIZONTAL_CENTER);/*设置格式 水平居中*/
        /*设置数据的边框 手册上写的方法只显示竖线 非常坑爹 所以采用网上搜来的方法*/
        $style_array = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN
                )
            )
        );
        $objPHPExcel->getActiveSheet()->getStyle('A1:F' . $mynumdata)->applyFromArray($style_array);

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(12);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(66);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        // $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(5);
        $objPHPExcel->getActiveSheet()->getStyle('A1:F' . $myrow)->getAlignment()->setWrapText(true); //设置单元格允许自动换行
        /*设置表相关的信息*/
        // $objPHPExcel->getActiveSheet()->setTitle('test_2333'); //活动表的名称
        $objPHPExcel->setActiveSheetIndex(0); //设置第一张表为活动表
        //纸张方向和大小 为A4横向
        $objPHPExcel->getActiveSheet()->getPageSetup()->setOrientation(\PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
        $objPHPExcel->getActiveSheet()->getPageSetup()->setPaperSize(\PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4);
        $file_name = '分销导出-' . date('Ymds') . '.xlsx';
        //浏览器交互 导出
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $file_name . '"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }





    /**
     * 编辑
     */
    public function koudan($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $koudan = Db::name('koudan')->where('user_id', $row->user_id)->find();



        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }


                    if ($koudan) {
                        $arr = ['rule_num' => $params['rule_num']];
                        if ($params['rule_num'] !== $koudan['rule_num']) {
                            $arr['num'] = '';
                            $arr['num1'] = 0;
                            $arr['updatetime'] = time();
                        }
                        $result = Db::name('koudan')->where('id', $koudan['id'])->update($arr);
                    } else {
                        $arr = [
                            'user_id' => $row->user_id,
                            'rule_num' => $params['rule_num'],
                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                        $result = Db::name('koudan')->insert($arr);
                    }


                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }



        $this->view->assign("row", $row);
        $this->view->assign("koudan", $koudan);
        return $this->view->fetch();
    }
}
